package org.swingDemo.UI.panel;

import net.miginfocom.swing.MigLayout;
import org.swingDemo.UI.MainFrame;
import org.swingDemo.util.IconUtil;
import org.swingDemo.util.UIUtil;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.util.prefs.Preferences;

public class OpenFolderPanel extends JPanel {

    private JButton openButton;

    public OpenFolderPanel() {
        initPanel();
    }

    private void initPanel() {
        openButton = UIUtil.createButton("打开目录", IconUtil.OpenFolderIcon, e -> {
            openFolder();
        });
        // 放大打开按钮的字体
        final Font font = openButton.getFont();
        openButton.setFont(font.deriveFont(font.getSize() * 4.0f));

        this.setLayout(new MigLayout("fill"));
        this.add(openButton, "w 400, h 200, center");
    }

    private void openFolder() {
        final Preferences preferences = Preferences.userRoot().node(getClass().getName());
        String key = "lastFolderPath";
        final String folderPath = preferences.get(key, "");
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setCurrentDirectory(new File(folderPath));
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        final int option = fileChooser.showOpenDialog(MainFrame.mainFrame);
        if (option == JFileChooser.APPROVE_OPTION) {
            final File selectedFile = fileChooser.getSelectedFile();
            preferences.put(key, selectedFile.getAbsolutePath());
            MainFrame.mainFrame.displayFolder(selectedFile);
        }
    }
}
